package com.taobao.diamond.server.utils;

import com.taobao.diamond.domain.Page;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

public class PaginationHelper<E>
{
    public Page<E> fetchPage(JdbcTemplate jt, String sqlCountRows, String sqlFetchRows, Object[] args, int pageNo, int pageSize, final ParameterizedRowMapper<E> rowMapper)
    {
        if (pageSize == 0) {
            return null;
        }

        int rowCount = jt.queryForInt(sqlCountRows, args);

        int pageCount = rowCount / pageSize;
        if (rowCount > pageSize * pageCount) {
            pageCount++;
        }

        final Page page = new Page();
        page.setPageNumber(pageNo);
        page.setPagesAvailable(pageCount);
        page.setTotalCount(rowCount);

        if (pageNo > pageCount) {
            return null;
        }
        int startRow = (pageNo - 1) * pageSize;

        String selectSQL = sqlFetchRows + " limit " + startRow + "," + pageSize;
        jt.query(selectSQL, args, new ResultSetExtractor() {
            public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
                List pageItems = page.getPageItems();
                int currentRow = 0;
                while (rs.next()) {
                    pageItems.add(rowMapper.mapRow(rs, currentRow++));
                }
                return page;
            }
        });
        return page;
    }
}